import React, {Component} from 'react';
import './style/index.less'
import {Form, Input, Button, Modal, message} from 'antd';
import {UserOutlined, LockOutlined} from '@ant-design/icons';
import $http from '../untils/request'

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            form: {
                username: '',
                password: ''
            },
            username: 'admin',
            password: '123456'
        }
    }

    componentDidMount() {
        this.getlogin()
    }

    render() {
        return (
            <div className='login'>
                <div className='login_box'>
                    <div className='login_box_title'>
                        <h2>Welcome Login!</h2>
                    </div>
                    <div>
                        <Form className='login_form'>
                            <Form.Item className='login_form_item' rules={[{required: true}]}>
                                <Input defaultValue={this.state.username}
                                       onChange={(event) => {
                                           this.setState({
                                               username: event.target.value
                                           })
                                       }}
                                       placeholder='用户名'></Input>
                            </Form.Item>
                            <Form.Item className='login_form_item'>
                                <Input.Password
                                    defaultValue={this.state.password}
                                    onChange={(event) => {
                                        this.setState({
                                            password: event.target.value
                                        })
                                    }}
                                    placeholder='密码'></Input.Password>
                            </Form.Item>
                            <Form.Item className='login_form_item'>
                                <Button onClick={() => this.onLogin()} type="primary" htmlType="submit"
                                        style={{width: '100%'}}>登录</Button>
                            </Form.Item>
                        </Form>
                    </div>
                    <div className='login_footer'>
                        <span onClick={() => this.onRegister()}>注册</span>
                    </div>
                </div>
                <Modal
                    title="注册"
                    okText="确认"
                    cancelText="取消"
                    maskClosable={false}
                    visible={this.state.visible}
                    onCancel={() => this.clearForm()}
                    onOk={() => this.submitForm()}
                >
                    <Form className='login_form' ref='form' labelCol={{xs: {span: 15,}, sm: {span: 3,},}}
                          initialValues={{...this.state.form}}>
                        <Form.Item className='login_form_item' rules={[{required: true}]} label='用户名' name='username'>
                            <Input
                                onChange={(event) => this.onInputChange(event, 'username')}
                                placeholder='请输入用户名'></Input>
                        </Form.Item>
                        <Form.Item className='login_form_item' label='密码' name='password'>
                            <Input.Password
                                onChange={(event) => this.onInputChange(event, 'password')}
                                placeholder='6到16位字符'></Input.Password>
                        </Form.Item>

                    </Form>
                </Modal>
            </div>
        );
    }

    async onLogin() {
        const data = {
            account: this.state.username,
            password: this.state.password
        }
        const res = await $http.post('/login', data)
        console.log(res)
        if (res.status === 200) {
            message.success(res.msg)
            sessionStorage.setItem('userInfo', JSON.stringify(res.data))
            sessionStorage.setItem('props', JSON.stringify(this.props.history))
            this.props.history.push('/myCenter/setInfo')
        } else {
            message.error(res.msg)
        }
    }

    clearForm() {
        const data = Object.assign({}, this.state.form, {
            username: '',
            password: ''
        })
        this.refs.form.setFieldsValue({
            username: '',
            password: ''
        })
        this.setState({
            form: data,
            visible: false,
        })
    }

    async getlogin() {
        const res = await $http.get('/getLoginToken')
        console.log(res)
        if (res.status === 200) {
            this.getToken()
        }
    }

    getToken() {
        const cookie = document.cookie
        if (cookie) {
            let value = cookie.split('Token=')[1].split(';')[0]
            sessionStorage.setItem('csrf-token', value)
        }
    }

    onInputChange(e, name) {
        e.persist()
        if (e.target.value) {
            this.setState((state, props) => {
                state.form[name] = e.target.value
            })
        }
    }

    onRegister() {
        this.setState({
            visible: true
        })
    }

    async submitForm() {
        const data = {
            account: this.state.form.username,
            password: this.state.form.password,
            registerTime: new Date().getTime()
        }
        const res = await $http.post('/register', data)
        if (res.status === 200) {
            message.success(res.msg)
            // this.clearForm()
        } else {
            message.error(res.msg)
        }
    }


}

export default Login;
